import { dialog } from "electron";
//引入node原生fs模块
const fs = require("fs");
// 引入node内置的path模块
const path = require("path");
/* 需要读写的文件地址 */
const file_path = path.join(process.cwd(), "/lib/mm.md");
// 选择文件
export function openDialog(mainWindow) {
  return new Promise((resolve, reject) => {
    dialog
      .showOpenDialog(mainWindow, {
        properties: ["openFile"],
      })
      .then((result) => {
        resolve(result);
      })
      .catch((err) => {
        return reject(err);
      });
  });
}
export function openSaveDialog(mainWindow, { file, title }) {
  return new Promise((resolve, reject) => {
    dialog
      .showSaveDialog(mainWindow, {
        defaultPath: title,
      })
      .then((result) => {
        if (!result.canceled) {
          fs.writeFileSync(result.filePath, file);
          resolve(result.filePath);
        }
      })
      .catch((err) => {
        return reject(err);
      });
  });
}
// 读取配置文件
export function readFile(path: string) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, "utf8", function (err, dataStr) {
      if (err) return reject(err.message); //读取失败
      /* application.properties  文件内容符合ini配置文件的格式，
      就可以通过ini.parse把读取到的文件转成js可识别的对象 */
      // resolve(ini.parse(dataStr.toString()));
      resolve(dataStr);
    });
  });
}
// 更改配置文件
export function writeFile(path, config: string) {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, config, function (err) {
      if (err) return reject(err.message); //写入失败
      resolve("写入成功");
    });
  });
}

// 使用nodejs 给文件重命名
export function reNameFile(path, newPath) {
  return new Promise((resolve, reject) => {
    fs.rename(path, newPath, function (err) {
      if (err) return reject(err.message);
      resolve("重命名成功");
    });
  });
}
